package com.panlin.printer.utils;

import android.graphics.Bitmap;

public class BitmapUtils {

    public static Bitmap convertToBlackAndWhite(Bitmap img) {
        int width = img.getWidth();
        int height = img.getHeight();
        int[] pixels = new int[width * height];
        int alpha = -16777216;
        int tmp = 130;
        img.getPixels(pixels, 0, width, 0, 0, width, height);

        for(int i = 0; i < height; ++i) {
            for(int j = 0; j < width; ++j) {
                int original = pixels[width * i + j];
                int red = (original & 16711680) >> 16;
                int green = (original & '\uff00') >> 8;
                int blue = original & 255;
                if (red > tmp) {
                    red = 255;
                } else {
                    red = 0;
                }

                if (blue > tmp) {
                    blue = 255;
                } else {
                    blue = 0;
                }

                if (green > tmp) {
                    green = 255;
                } else {
                    green = 0;
                }

                int grey = (int)((double)((float)red) * 0.3 + (double)((float)green) * 0.59 + (double)((float)blue) * 0.11);
                grey = alpha | grey << 16 | grey << 8 | grey;
                pixels[width * i + j] = grey;
            }
        }

        Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        result.setPixels(pixels, 0, width, 0, 0, width, height);
        return result;
    }
}
